package c.x.jy.service.utils.wechat;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import c.x.jy.common.exception.RRException;
import c.x.jy.dao.entity.MemberEntity;

/**
 * 微信绑定微信用户并进行网页授权
 * Created by luomin on 2017/1/9 14:54.
 */
public class WechatAuthorizeUtils {

	   protected static Logger logger = LoggerFactory.getLogger(WechatAuthorizeUtils.class);

    //scope为snsapi_base发起的授权
    public static  String getCodeBySnsapiBase(String url,WechatConfig userConfig) throws UnsupportedEncodingException{
    	url=URLEncoder.encode(url,"UTF-8");
    	return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=1#wechat_redirect",userConfig.getGzhAppId(),url);
    }
    
    //scope为snsapi_base发起的授权
    public static  String getCodeBySnsapiBase(String url,String appid) throws UnsupportedEncodingException{
    	url=URLEncoder.encode(url,"UTF-8");
    	return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=1#wechat_redirect",appid,url);
    }

/*    //scope为snsapi_userinfo 发起的授权
    public static  String getCodeBySnsapiUserInfo(String url) throws UnsupportedEncodingException{
    	url=URLEncoder.encode(url,"UTF-8");
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s"
               +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect",GetConfig.getAppId(),url);
    	//return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
       // + wechatConfigEntity.getAppId() + "&redirect_uri="
       // + url + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    }*/
    
    //scope为snsapi_userinfo 发起的授权
    public static  String getCodeBySnsapiUserInfo(String url,	WechatConfig userConfig) throws UnsupportedEncodingException{
    	url=URLEncoder.encode(url,"UTF-8");
    	
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s"
               +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect",userConfig.getGzhAppId(),url);
    	//return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
       // + wechatConfigEntity.getAppId() + "&redirect_uri="
       // + url + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    }

    /**
     * 通过code得到用户openId
     * @param code
     * @return openId
     * @throws IOException
     */
/*    public static AccessTokenData getUserOpenIdByCode(String code) throws Exception {
    	  AccessTokenData accessToken = new AccessTokenData();
          String url= String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
        		  GetConfig.getAppId(),GetConfig.getAppSecret(),code);
          String resultStr = WechatCommonUtil.sendGet(url);    
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if(jsonObject.getString("errcode")!=null){
        	logger.error("resultStr:{}",resultStr);
        	return null;
        }
    //  System.out.println("getUserOpenIdByCode"+jsonObject.toJSONString());
        accessToken.setAccessToken(jsonObject.getString("access_token"));
        accessToken.setOpenId(jsonObject.getString("openid"));
        accessToken.setExpiresIn(Long.parseLong(jsonObject.getString("expires_in")));
        accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
        accessToken.setScope(jsonObject.getString("scope"));
        return  accessToken;
    }*/


    /**
     * 获取用户信息(昵称 头像 性别 国家 省 城市 )
     * 需要用户授权
     * @param code
     * @return
     * @throws Exception
    
     public static WechatUserData getUserData(String code) throws Exception{
       AccessTokenData accessTokenData = getUserOpenIdByCode(code);
        WechatUserData wechatUserData = new WechatUserData();
        String accessToken = accessTokenData.getAccessToken();//网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
        String openId = accessTokenData.getOpenId();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
        String resultStr = WechatCommonUtil.sendGet(String.format(url,accessToken,openId));
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if(jsonObject.getString("errcode")!=null){
        	logger.error("resultStr:{}",resultStr);
        	return null;
        }
        wechatUserData.setOpenId(openId);
        wechatUserData.setNickName(jsonObject.getString("nickname"));
        String sexStr = jsonObject.getString("sex");
        if( sexStr!=null&&!sexStr.trim().equals("")){
            wechatUserData.setSex(Integer.parseInt(sexStr));
        } 
        wechatUserData.setProvince(jsonObject.getString("province"));
        wechatUserData.setCity(jsonObject.getString("city"));
        wechatUserData.setCountry(jsonObject.getString("country"));
        wechatUserData.setHeadimgurl(jsonObject.getString("headimgurl"));
        wechatUserData.setPrivilege(jsonObject.getString("privilege"));
        wechatUserData.setUnionid(jsonObject.getString("unionid"));
        return  wechatUserData;
    }
    */
    public static String getUserOpenId(String code,	String appid,String appSecret)throws Exception{
	
    	 // AccessTokenData accessToken = new AccessTokenData();
          String url= String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
        		  appid,appSecret,code);
          String resultStr = WechatCommonUtil.sendGet(url);
    
          JSONObject jsonObject = JSONObject.parseObject(resultStr);
      	logger.error("resultStr:{}",resultStr);
          if(jsonObject.getString("errcode")!=null){
	        	logger.error("resultStr:{}",resultStr);
	        	return null;
	        }
    	return jsonObject.getString("openid");
    }

    public static AccessTokenData getUserOpenId1(String code,	String appid,String appSecret)throws Exception{
  	  AccessTokenData accessToken = new AccessTokenData();
        String url= String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
      		  appid,appSecret,code);
        
        String resultStr = WechatCommonUtil.sendGet(url);
        logger.error("resultStr:{}",resultStr);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if(jsonObject.getString("errcode")!=null){
        	logger.error("resultStr:{}",resultStr);
        	throw new RRException(jsonObject.getString("errcode"));
        }
        accessToken.setAccessToken(jsonObject.getString("access_token"));
        accessToken.setOpenId(jsonObject.getString("openid"));
      //  accessToken.setExpiresIn(Long.parseLong(jsonObject.getString("expires_in")));
        accessToken.setRefreshToken(jsonObject.getString("refresh_token"));
        accessToken.setScope(jsonObject.getString("scope"));
  	return accessToken;
  	
  	
  }
    
	public static MemberEntity getUserData1(String code, WechatConfig userConfig) throws Exception {
		AccessTokenData 	accessTokenData	=WechatAuthorizeUtils.getUserOpenId1(code, userConfig.getGzhAppId(),userConfig.getGzhAppSecret());
		return getuserbyOpenid(accessTokenData);
	}
    
	
	public static MemberEntity getuserbyOpenid(AccessTokenData accessTokenData ) throws Exception {
	//	WechatUserData wechatUserData = new WechatUserData();
		if(accessTokenData==null||StringUtils.isEmpty(  accessTokenData.getAccessToken())) {
			throw new RRException("网页已经过期！请重新刷新");
		}
	        String accessToken = accessTokenData.getAccessToken();//网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
	        String openId = accessTokenData.getOpenId();
	        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
	       

	        String resultStr = WechatCommonUtil.sendGet(String.format(url,accessToken,openId));
	        logger.info("resultStr:{}",resultStr);
	        MemberEntity memger = JSONObject.parseObject(resultStr,MemberEntity.class);
	        logger.info("jsonObject:{}",memger);
		 
	        return  memger;
	}




	

}
